package com.dlc.shop.service.impl;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dlc.shop.allinpay.service.AllinpayCompanyService;
import com.dlc.shop.bean.app.param.ShopAuditingParam;
import com.dlc.shop.bean.dto.allinpay.UpdateCompanyInfoDTO;
import com.dlc.shop.bean.enums.AuditStatus;
import com.dlc.shop.bean.model.CompanyAuditing;
import com.dlc.shop.bean.model.ShopAuditing;
import com.dlc.shop.bean.model.ShopCompany;
import com.dlc.shop.bean.model.ShopDetail;
import com.dlc.shop.bean.param.CompanyInfoAuditParam;
import com.dlc.shop.bean.vo.ShopCompanyVO;
import com.dlc.shop.common.allinpay.constant.*;
import com.dlc.shop.common.allinpay.member.resp.CompanyInfo;
import com.dlc.shop.common.allinpay.member.resp.UpdateCompanyInfoResp;
import com.dlc.shop.common.config.Constant;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.common.util.BeanUtil;
import com.dlc.shop.common.util.PrincipalUtil;
import com.dlc.shop.config.ShopConfig;
import com.dlc.shop.dao.CompanyAuditingMapper;
import com.dlc.shop.dao.ShopDetailMapper;
import com.dlc.shop.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * @author chiley
 * @date 2022/9/21 15:00
 */
@Service
public class CompanyAuditingServiceImpl extends ServiceImpl<CompanyAuditingMapper, CompanyAuditing> implements CompanyAuditingService {
    private static final Logger logger = LoggerFactory.getLogger(CompanyAuditingServiceImpl.class);

    @Autowired
    @Lazy
    private ShopCompanyService shopCompanyService;
    @Autowired
    private CompanyAuditingMapper companyAuditingMapper;
    @Autowired
    private ShopDetailMapper shopDetailMapper;
    @Autowired
    @Lazy
    private ShopDetailService shopDetailService;
    @Autowired
    private AllinpayCompanyService allinpayCompanyService;
    @Autowired
    @Lazy
    private ShopBankCardService shopBankCardService;
    @Autowired
    private ShopAuditingService shopAuditingService;
    @Autowired
    private ShopConfig shopConfig;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void applyChangeCompanyInfo(ShopCompany shopCompany, String userId) {
        ShopDetail shopDetail = shopDetailMapper.selectShopDetailById(shopCompany.getShopId());
        ShopCompanyVO shopCompanyVO = new ShopCompanyVO();
        if (allinpayCompanyService.getIsAllinpay()) {
            if (!Objects.equals(shopDetail.getIdCardCollectProcessStatus(), IdCardCollectProcessStatus.ALL.value())) {
                logger.info("获取影印件还未通过的商家{}工商信息，状态为待审核", shopCompany.getShopId());
                shopCompanyVO = shopCompanyService.getShopCompanyByShopIdAndStatus(shopCompany.getShopId(), AuditStatus.WAITAUDIT.value());
            } else {
                logger.info("获取影印件已经通过的商家{}工商信息，状态为审核成功", shopCompany.getShopId());
                shopCompanyVO = shopCompanyService.getShopCompanyByShopIdAndStatus(shopCompany.getShopId(), AuditStatus.SUCCESSAUDIT.value());
            }
        }
        if (StrUtil.isNotBlank(shopCompany.getLegalPhone())) {
            if (!PrincipalUtil.isDbPhone(shopCompany.getLegalPhone(), shopCompanyVO.getLegalPhone(), true)) {
                throw new YamiShopBindException("yami.user.err.phone");
            }
            if (shopCompany.getLegalPhone().contains(Constant.ASTERISK)) {
                shopCompany.setLegalPhone(shopCompanyVO.getLegalPhone());
            }
        }
        // 把之前审核不通过的工商信息删除
        shopCompanyService.remove(new LambdaQueryWrapper<ShopCompany>().eq(ShopCompany::getShopId, shopCompany.getShopId()).eq(ShopCompany::getStatus, AuditStatus.FAILAUDIT.value()));
        // 保存变更工商信息
        shopCompany.setStatus(AuditStatus.WAITAUDIT.value());
        shopCompanyService.saveInfo(shopCompany);
        // 生成审核信息
        Long companyAuditingId = generateAuditInformation(shopCompany, userId);
        if (allinpayCompanyService.getIsAllinpay()) {
            if (Objects.equals(shopDetail.getCompanyInfoProcessStatus(), CompanyInfoProcessStatus.SUCCESS.value())) {
                logger.info("商家{}工商信息已经通过审核，更新工商信息内容和状态和后续处理", shopCompany.getShopId());
                // 审核成功的要进行更改的
                updateCompany(shopCompany, companyAuditingId, shopCompanyVO, shopDetail);
            }
        }
    }

    private void updateCompany(ShopCompany shopCompanyDTO, Long companyAuditingId, ShopCompanyVO shopCompanyVO, ShopDetail shopDetail) {
        Long shopId = shopCompanyDTO.getShopId();
        CompanyInfo companyInfo = allinpayCompanyService.getCompanyInfo(AllinpayConstant.SHOP + shopId);
        Integer idCardStatus = allinpayCompanyService.getIdCardStatus(companyInfo.getOcrRegnumComparisonResult(), companyInfo.getOcrIdcardComparisonResult());

        if (!Objects.equals(shopDetail.getIdCardCollectProcessStatus(), idCardStatus)) {
            logger.info("商家{}影印件信息状态{}和通联影印件信息状态{}不一致，处理影印件状态", shopCompanyDTO.getShopId(),
                    shopDetail.getIdCardCollectProcessStatus(), idCardStatus);
            // 不一致先更新
            shopDetailService.updateAllinpayIdCardStatus(AllinpayConstant.SHOP + shopId, idCardStatus);
        }
        // 信用代码不能更改
        if (Objects.nonNull(shopCompanyVO) && !Objects.equals(shopCompanyDTO.getCreditCode(), shopCompanyVO.getCreditCode())) {
            throw new YamiShopBindException("信用代码不可更改");
        }
        // 改了基本信息
        boolean isChangeInfo = getIsChangeInfo(shopCompanyDTO, shopCompanyVO);
        // 改了关键信息
        boolean isChangeKeyInfo = getIsChangeKeyInfo(shopCompanyDTO, shopCompanyVO);
        // 改了影印件
        boolean isChangeIdCard = getIsChangeIdCard(BeanUtil.map(shopCompanyDTO, ShopCompanyVO.class), shopCompanyVO);
        if (!isChangeInfo && !isChangeKeyInfo && !isChangeIdCard) {
            // 没有改通联有关信息直接审核成功
            logger.info("没有修改通联有关信息，店铺{}工商信息审核通过", shopId);
            audit(new CompanyAuditing(companyAuditingId, AuditStatus.SUCCESSAUDIT.value(), ""));
            return;
        }

        if (isChangeInfo || isChangeKeyInfo) {
            logger.info("商家修改了基本信息{}或关键信息{}，交给通联审核", isChangeInfo, isChangeKeyInfo);
            // 对于信息修改操作，上送所有需修改信息均认证成功才操作修改，否则信息均不修改；
            UpdateCompanyInfoDTO updateCompanyInfoDTO = new UpdateCompanyInfoDTO(AllinpayConstant.SHOP + shopId);
            updateCompanyInfoDTO.setCompanyName(shopCompanyDTO.getFirmName());
            updateCompanyInfoDTO.setCompanyAddress(shopCompanyDTO.getResidence());
            updateCompanyInfoDTO.setLegalPhone(shopCompanyDTO.getLegalPhone());
            updateCompanyInfoDTO.setLegalIds(shopCompanyDTO.getLegalIds());
            updateCompanyInfoDTO.setLegalName(shopCompanyDTO.getRepresentative());
            // 通联审核
            String domainUrl = shopConfig.getDomain().getApiDomainName();
            String backUrl = domainUrl + AllinpayNoticeUrl.UPDATE_COMPANY_INFO;
            UpdateCompanyInfoResp updateCompanyInfoResp = allinpayCompanyService.updateCompanyInfo(shopId, backUrl, updateCompanyInfoDTO);
            if (Objects.equals(updateCompanyInfoResp.getResult(), AuditStatus.SUCCESS.value())) {
                logger.info("通联审核店铺{}修改的工商信息成功", shopId);
                if (isChangeKeyInfo) {
                    logger.info("店铺{}修改了关键信息，并且审核通过，更新店铺为通联上线待审核，等待影印件重新审核通过", shopId);
                    // 修改了会触发ocr的
                    //审核成功 通联更新了企业信息 更新会触发ocr，店铺需要下线等待影印件审核通过
                    audit(new CompanyAuditing(companyAuditingId, AuditStatus.SUCCESSAUDIT.value(), ""));
                    // 更新店铺为通联上线待审核，影印件审核通过即可营业
                    shopDetailMapper.updateShopToWaitAudit(shopCompanyDTO.getShopId());
                } else if (!isChangeIdCard) {
                    logger.info("店铺{}没有修改了关键信息，也没有影印件要上传，直接审核成功", shopId);
                    // 没有修改关键信息,没有上传影印件可以直接成功
                    audit(new CompanyAuditing(companyAuditingId, AuditStatus.SUCCESSAUDIT.value(), ""));
                    if (!Objects.equals(shopDetail.getIdCardCollectProcessStatus(), IdCardCollectProcessStatus.ALL.value())) {
                        logger.info("店铺{}影印件状态异常，更新影印件", shopId);
                        shopDetailService.updateAllinpayIdCardStatus(AllinpayConstant.SHOP + shopId, idCardStatus);
                    }
                    return;
                }
            } else if (Objects.equals(updateCompanyInfoResp.getResult(), AuditStatus.FAIL.value())) {
                logger.info("通联审核店铺{}修改的工商信息失败，拒绝更新", shopId);
                // 审核失败不会更新影印件审核，只需要拒绝更新就可以了
                audit(new CompanyAuditing(companyAuditingId, AuditStatus.FAILAUDIT.value(), updateCompanyInfoResp.getFailReason()));
                return;
            }
        }

        // 如果有改变影印件，没有改变别的信息，在这里影印件需要重新上传，上传失败拒绝更新
        onlyChangeIdCard(shopCompanyDTO, companyAuditingId, shopDetail, shopId, idCardStatus, isChangeInfo, isChangeKeyInfo);
    }

    private void onlyChangeIdCard(ShopCompany shopCompanyDTO, Long companyAuditingId, ShopDetail shopDetail, Long shopId, Integer idCardStatus,
                                  boolean isChangeInfo, boolean isChangeKeyInfo) {
        if (!isChangeInfo && !isChangeKeyInfo) {
            logger.info("店铺{}只修改影印件，影印件上传", shopId);
            if (!Objects.equals(shopDetail.getIdCardCollectProcessStatus(), idCardStatus) && Objects.equals(idCardStatus, IdCardCollectProcessStatus.ALL.value())) {
                logger.info("店铺{}影印件已经通过审核，但是店铺影印件状态没更新，更新状态并且拒绝影印件上传审核", shopId);
                // 如果影印件上传成功但是这里没有更新的话要更新一下
                audit(new CompanyAuditing(companyAuditingId, AuditStatus.FAILAUDIT.value(), "店铺影印件已经审核通过，无需更新"));
                shopDetailService.updateAllinpayIdCardStatus(AllinpayConstant.SHOP + shopId, idCardStatus);
                return;
            } else if (!Objects.equals(shopDetail.getIdCardCollectProcessStatus(), idCardStatus)) {
                logger.info("店铺{}影印件状态没更新，更新状态", shopId);
                shopDetailService.updateAllinpayIdCardStatus(AllinpayConstant.SHOP + shopId, idCardStatus);
            } else if (Objects.equals(shopDetail.getIdCardCollectProcessStatus(), IdCardCollectProcessStatus.ALL.value())) {
                logger.info("店铺{}影印件已经通过审核，拒绝影印件上传审核", shopId);
                audit(new CompanyAuditing(companyAuditingId, AuditStatus.FAILAUDIT.value(), "店铺影印件已经审核通过，无需更新"));
                return;
            }
            String result = shopCompanyService.idCardCollect(BeanUtil.map(shopCompanyDTO, ShopCompanyVO.class), shopId);
            if (!Objects.equals(result, AllinpayConstant.ALLINPAY_AUDIT_SUCCESS)) {
                logger.info("店铺{}影印件上传失败，拒绝影印件更新", shopId);
                audit(new CompanyAuditing(companyAuditingId, AuditStatus.FAILAUDIT.value(), "店铺影印件上传失败，请重新上传"));
                return;
            }
            // 更新店铺为通联上线待审核，影印件审核通过即可营业
            shopDetailMapper.updateShopToWaitAudit(shopCompanyDTO.getShopId());
            // 更新店铺影印件采集状态
            shopDetailMapper.updateAllinpayIdCardStatus(shopCompanyDTO.getShopId(), IdCardCollectProcessStatus.WAIT_AUDIT.value());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void revoke(CompanyAuditing companyAuditing) {
        if (!Objects.equals(companyAuditing.getStatus(), AuditStatus.WAITAUDIT.value())) {
            throw new YamiShopBindException("yami.Auditing.applicationInfo.notFound");
        }
        // 删除申请变更的工商信息
        shopCompanyService.remove(new LambdaQueryWrapper<ShopCompany>().eq(ShopCompany::getShopCompanyId, companyAuditing.getShopCompanyId()));
        // 删除申请审核信息
        removeById(companyAuditing.getCompanyAuditingId());
    }

    @Override
    public IPage<CompanyAuditing> page(Page<CompanyAuditing> page, CompanyInfoAuditParam companyInfoAuditParam) {
        return companyAuditingMapper.page(page, companyInfoAuditParam);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void audit(CompanyAuditing companyAuditing) {
        CompanyAuditing companyAuditingDb = companyAuditingMapper.selectById(companyAuditing.getCompanyAuditingId());
        if (Objects.isNull(companyAuditingDb) || !Objects.equals(companyAuditingDb.getStatus(), AuditStatus.WAITAUDIT.value())) {
            throw new YamiShopBindException("yami.Auditing.applicationInfo.notFound");
        }
        // 审核不通过
        if (Objects.equals(companyAuditing.getStatus(), AuditStatus.FAILAUDIT.value())) {
            companyAuditing.setStatus(AuditStatus.FAILAUDIT.value());
            companyAuditing.setRemarks(companyAuditing.getRemarks());
            companyAuditingMapper.updateById(companyAuditing);
            // 把对应的工商信息设置为审核未通过状态
            shopCompanyService.update(new LambdaUpdateWrapper<ShopCompany>().set(ShopCompany::getStatus, AuditStatus.FAILAUDIT.value()).eq(ShopCompany::getShopCompanyId, companyAuditing.getShopCompanyId()));
            return;
        }
        // 审核通过(if不能省略，防止传入非法参数)
        if (Objects.equals(companyAuditing.getStatus(), AuditStatus.SUCCESSAUDIT.value())) {
            companyAuditing.setStatus(AuditStatus.SUCCESSAUDIT.value());
            companyAuditingMapper.updateById(companyAuditing);
            // 把之前审核不通过的工商信息删除
            shopCompanyService.remove(new LambdaQueryWrapper<ShopCompany>().eq(ShopCompany::getShopId, companyAuditing.getShopId()).ne(ShopCompany::getShopCompanyId, companyAuditingDb.getShopCompanyId()));
            // 把对应的工商信息设置为启用状态
            shopCompanyService.update(new LambdaUpdateWrapper<ShopCompany>().set(ShopCompany::getStatus, AuditStatus.SUCCESSAUDIT.value()).eq(ShopCompany::getShopCompanyId, companyAuditingDb.getShopCompanyId()));
        }
    }

    @Override
    public CompanyAuditing getAuditInfo(Long shopId) {
        CompanyAuditing latestCompanyAuditing = getOne(new LambdaQueryWrapper<CompanyAuditing>().eq(CompanyAuditing::getShopId, shopId).orderByDesc(CompanyAuditing::getCreateTime), false);
        if (Objects.isNull(latestCompanyAuditing)) {
            return new CompanyAuditing();
        }
        latestCompanyAuditing.setShopCompany(shopCompanyService.getById(latestCompanyAuditing.getShopCompanyId()));
        return latestCompanyAuditing;
    }

    @Override
    public CompanyAuditing getLatestAuditingByShopId(Long shopId) {
        return companyAuditingMapper.selectOne(new LambdaQueryWrapper<CompanyAuditing>()
                .eq(CompanyAuditing::getShopId, shopId).orderByDesc(CompanyAuditing::getCreateTime).last("limit 1"));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCompanyInfoResult(String bizUserId, Integer status, Integer result, String failReason) {
        Long shopId = Long.valueOf(bizUserId.substring(AllinpayConstant.SHOP_LENGTH));
        ShopCompanyVO waitAuditShopCompany = shopCompanyService.getShopCompanyByShopIdAndStatus(shopId, AuditStatus.WAITAUDIT.value());
        ShopCompanyVO successShopCompany = shopCompanyService.getShopCompanyByShopIdAndStatus(shopId, AuditStatus.SUCCESSAUDIT.value());
        CompanyAuditing shopCompanyAuditingVO = getLatestAuditingByShopId(shopId);
        // 更新失败
        if (Objects.equals(result, AuditStatus.FAIL.value())) {
            logger.info("通联回调审核店铺{}修改的工商信息失败，拒绝更新，原因为{}", shopId, failReason);
            audit(new CompanyAuditing(shopCompanyAuditingVO.getCompanyAuditingId(), AuditStatus.FAILAUDIT.value(), failReason));
        }
        // 更新成功
        else if (Objects.equals(result, AuditStatus.SUCCESS.value())) {
            // 如果有改变企业名称，法人名称，需要重新签约提现协议
            checkChangeName(waitAuditShopCompany, successShopCompany, shopId);
            if (getIsChangeIdCard(waitAuditShopCompany, successShopCompany)) {
                logger.info("通联回调审核店铺{}修改的工商信息成功，修改了影印件，重新上传影印件", shopId);
                // 修改了影印件
                String idCardCollectResult = shopCompanyService.idCardCollect(waitAuditShopCompany, shopId);
                if (!Objects.equals(idCardCollectResult, AllinpayConstant.ALLINPAY_AUDIT_SUCCESS)) {
                    logger.info("通联回调审核店铺{}修改的工商信息成功，影印件上传异常，拒绝申请", shopId);
                    audit(new CompanyAuditing(shopCompanyAuditingVO.getCompanyAuditingId(), AuditStatus.FAILAUDIT.value(), "影印件上传异常，请重试"));
                    return;
                }
                // 更新店铺为通联上线待审核，影印件审核通过即可营业
                shopDetailMapper.updateShopToWaitAudit(shopId);
                // 更新店铺影印件采集状态
                shopDetailMapper.updateAllinpayIdCardStatus(shopId, IdCardCollectProcessStatus.WAIT_AUDIT.value());
            } else {
                logger.info("通联回调审核店铺{}修改的工商信息成功，没有修改影印件", shopId);
                if (!Objects.equals(status, IdCardCollectProcessStatus.ALL.value())) {
                    logger.info("通联回调审核店铺{}修改的工商信息成功，没有修改影印件，影印件ocr失败", shopId);
                    // 影印件ocr失败了，对店铺进行状态更新
                    // 更新店铺为通联上线待审核，影印件审核通过即可营业
                    shopDetailMapper.updateShopToWaitAudit(shopId);
                    // 更新店铺影印件采集状态
                    shopDetailMapper.updateAllinpayIdCardStatus(shopId, status);
                    return;
                }
                // 审核成功,影印件也成功
                audit(new CompanyAuditing(shopCompanyAuditingVO.getCompanyAuditingId(), AuditStatus.SUCCESSAUDIT.value(), ""));
            }
        }
    }

    private void checkChangeName(ShopCompanyVO shopCompanyDTO, ShopCompanyVO shopCompany, Long shopId) {
        if (!Objects.equals(shopCompany.getFirmName(), shopCompanyDTO.getFirmName())) {
            logger.info("通联回调审核店铺{}修改的工商信息成功，修改了企业名称，需要重新签约对公提现协议", shopId);
            shopDetailMapper.updateAcctProtocolNoByType(shopId, SignAcctType.COMPANY.getValue(), null);
        }
        if (!Objects.equals(shopCompany.getRepresentative(), shopCompanyDTO.getRepresentative())) {
            logger.info("通联回调审核店铺{}修改的工商信息成功，修改了法人姓名，需要重新签约法人提现协议", shopId);
            shopDetailMapper.updateAcctProtocolNoByType(shopId, SignAcctType.LEGAL_PERSON.getValue(), null);
        }
    }

    private boolean getIsChangeIdCard(ShopCompanyVO shopCompanyDTO, ShopCompanyVO shopCompany) {
        if (Objects.isNull(shopCompany)) {
            return true;
        }
        if (!Objects.equals(shopCompany.getIdentityCardFront(), shopCompanyDTO.getIdentityCardFront())) {
            return true;
        }
        if (!Objects.equals(shopCompany.getBusinessLicense(), shopCompanyDTO.getBusinessLicense())) {
            return true;
        }
        return !Objects.equals(shopCompany.getIdentityCardLater(), shopCompanyDTO.getIdentityCardLater());
    }

    private boolean getIsChangeInfo(ShopCompany shopCompanyDTO, ShopCompanyVO shopCompanyVO) {
        if (Objects.isNull(shopCompanyVO)) {
            return true;
        }
        if (!Objects.equals(shopCompanyDTO.getResidence(), shopCompanyVO.getResidence())) {
            return true;
        }
        return !Objects.equals(shopCompanyDTO.getLegalPhone(), shopCompanyVO.getLegalPhone());
    }

    private boolean getIsChangeKeyInfo(ShopCompany shopCompanyDTO, ShopCompanyVO shopCompanyVO) {
        if (Objects.isNull(shopCompanyVO)) {
            return true;
        }
        if (!Objects.equals(shopCompanyDTO.getRepresentative(), shopCompanyVO.getRepresentative())) {
            return true;
        }
        if (!Objects.equals(shopCompanyDTO.getFirmName(), shopCompanyVO.getFirmName())) {
            return true;
        }
        return !Objects.equals(shopCompanyDTO.getLegalIds(), shopCompanyVO.getLegalIds());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAllinpayShopStatus(String bizUserId, Integer status, String failReason) {
        Long shopId = Long.valueOf(bizUserId.substring(AllinpayConstant.SHOP_LENGTH));
        ShopDetail shopDetailVO = shopDetailService.getShopDetailByShopId(shopId);
        if (Objects.equals(status, AuditStatus.FAIL.value())) {
            logger.info("通联审核商家企业信息失败");
            if (Objects.equals(shopDetailVO.getAllinpayShopStatus(), AllinpayShopStatus.OFFLINE.value()) && Objects.equals(shopDetailVO.getCompanyInfoProcessStatus(), CompanyInfoProcessStatus.FAIL.value())) {
                logger.info("店铺{}状态已经处理过，无需下线处理", shopDetailVO.getShopName());
                return;
            }
            auditFail(bizUserId, failReason, shopId);
        } else if (Objects.equals(status, AuditStatus.SUCCESS.value())) {
            logger.info("通联审核商家企业信息成功");
            if (Objects.equals(shopDetailVO.getIdCardCollectProcessStatus(), IdCardCollectProcessStatus.ALL.value()) && Objects.equals(shopDetailVO.getCompanyInfoProcessStatus(), CompanyInfoProcessStatus.SUCCESS.value())) {
                return;
            }
            ShopCompanyVO shopCompany = shopCompanyService.getShopCompanyByShopIdAndStatus(shopId, AuditStatus.WAITAUDIT.value());
            // 审核成功 更新店铺状态
            shopBankCardService.updateShopAllinpayStatusToSuccess(shopId);
            if (!Objects.equals(shopDetailVO.getIdCardCollectProcessStatus(), IdCardCollectProcessStatus.ALL.value())) {
                // 调用影印件上传接口
                String idCardResult = "";
                try {
                    idCardResult = shopCompanyService.idCardCollect(shopCompany, shopId);
                } catch (Exception e) {
                    logger.error("店铺设置企业信息回调，影印件上传审核失败：{}", e.getMessage());
                }
                if (!Objects.equals(idCardResult, AllinpayConstant.ALLINPAY_AUDIT_SUCCESS)) {
                    logger.error("店铺设置企业信息回调，影印件上传审核失败：{}", idCardResult);
                }
            }
        }
        shopDetailService.removeShopDetailCacheByShopId(shopId);
    }

    private void auditFail(String bizUserId, String failReason, Long shopId) {
        CompanyAuditing companyAuditing = getLatestAuditingByShopId(shopId);
        if (Objects.nonNull(companyAuditing) && Objects.equals(companyAuditing.getStatus(), AuditStatus.WAITAUDIT.value())) {
            logger.info("店铺Id{}已经开店，通联审核失败，拒绝店铺的工商申请", shopId);
            // 如果是已经开店来审核的话要把审核拒绝通过
            audit(new CompanyAuditing(companyAuditing.getCompanyAuditingId(), AuditStatus.FAILAUDIT.value(), failReason));
        } else {
            logger.info("店铺Id{}还未开店，通联审核失败，拒绝店铺的开店申请", shopId);
            // 还未开店，审核失败
            ShopAuditing shopAuditing = shopAuditingService.getOne(new LambdaQueryWrapper<ShopAuditing>().eq(ShopAuditing::getShopId, shopId));
            ShopAuditingParam shopAuditingParam = new ShopAuditingParam();
            shopAuditingParam.setShopId(shopId);
            shopAuditingParam.setAuditorId(null);
            shopAuditingParam.setStatus(AuditStatus.FAILAUDIT.value());
            shopAuditingParam.setRemarks(failReason);
            shopDetailService.audit(shopAuditingParam);
        }
        // 更新审核失败——平台下线
        shopDetailMapper.updateShopAuditFail(shopId);
        logger.info("店铺id为{}通联审核失败原因：{}", bizUserId, failReason);
    }

    @Override
    public void updateRemark(CompanyAuditing companyAuditing) {
        update(new LambdaUpdateWrapper<CompanyAuditing>()
                .set(CompanyAuditing::getRemarks, companyAuditing.getRemarks())
                .set(CompanyAuditing::getStatus, companyAuditing.getStatus())
                .eq(CompanyAuditing::getCompanyAuditingId, companyAuditing.getCompanyAuditingId()));
    }

    @Override
    public List<CompanyAuditing> getNeedAuditList() {
        return companyAuditingMapper.getNeedAuditList();
    }

    /**
     * 生成店铺申请记录
     *
     * @param shopCompany
     * @param userId
     */
    private Long generateAuditInformation(ShopCompany shopCompany, String userId) {
        CompanyAuditing companyAuditing = new CompanyAuditing();
        companyAuditing.setShopId(shopCompany.getShopId());
        companyAuditing.setShopCompanyId(shopCompany.getShopCompanyId());
        companyAuditing.setUserId(userId);
        companyAuditing.setStatus(AuditStatus.WAITAUDIT.value());
        save(companyAuditing);
        return companyAuditing.getCompanyAuditingId();
    }
}
